#include "RedisRegister.h"
#include "rpcserver.h"
#include "tinyrpc/net/coroutine_function.h"
#include "tinyrpc/net/inetaddress.h"
namespace TinyRPC{
RedisRegister::RedisRegister()
:m_quit(false){

}
void RedisRegister::regist(std::unordered_map<std::string, ServiceInfo>& serviceMap, const INetAddress& serverAddress){
    std::string field = serverAddress.toString();
    for(auto& it : serviceMap){
        std::string key = KeyPrefix + it.first;
        
        m_redisClient.hset(key , field, "0");

        m_redisClient.setex(key + ":" + field, 600, "0");
        m_serviceList.insert({key, field});
        //m_subscribeChannels.push_back(key);
    }
    

}

//心跳包， 这个需要在协程里面使用
void RedisRegister::heartbeat(){
    while (!m_quit)
    {
        for(auto& it : m_serviceList){
            // std::string key = it.first;
            // key += it->second;
            m_redisClient.expire(it.first + ":" + it.second, 4);
        }
        coroutine_sleep(1);
    }
}

//这个需要在协程里面使用
// 订阅某几个频道， 监听事件
void RedisRegister::subscribe(){
    INetAddress redisAddress;
    SocketChannel socketChannel;
    socketChannel.connect(redisAddress);
    BufferPtr buffer = m_redisClient.coroutine_subscribe(socketChannel, m_subscribeChannels);
    
    std::string notice = buffer->read();
    

}
}